//
//  WCBPhoneLoginViewController.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/14.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCBPhoneLoginViewController.h"
#import "UIScreen+Extend.h"
#import "UIColor+Extend.h"
#import "UIView+Layout.h"
#import "WCASessionManager.h"
#import "WCBUtility.h"
#import "WCASessionManager.h"
#import "UserModel.h"
#import "WCBDataHelper.h"
#import "TFToast.h"

#import "WCBCaptureDataViewController.h"
#import "WCBAddressListTableViewController.h"

@interface WCBPhoneLoginViewController ()

/**
 手机号输入框
 */
@property(nonatomic,strong) UITextField * phoneTextField;

/**
 验证码输入框
 */
@property(nonatomic,strong) UITextField *verificationTextField;

/**
 获取验证码 按钮
 */
@property (nonatomic,strong) UIButton *getVerificationBtn;

/**
 登录按钮
 */
@property (nonatomic,strong) UIButton *loginBtn;

/**
 60s 的总时间
 */
@property(assign, nonatomic) NSInteger timeCount;

@property (nonatomic ,strong) UIActivityIndicatorView *activityIndicatorView;

@property (nonatomic,strong) NSTimer *timer;

@end

@implementation WCBPhoneLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    self.view.backgroundColor = [UIColor r:239 g:239 b:239];
    [self p_setUpSubViews];
    
    [WCBDataHelper sharedHelper];
}

- (void)p_setUpSubViews{
    
    [self.view addSubview:self.phoneTextField];
    [self.view addSubview:self.verificationTextField];
    [self.view addSubview:self.getVerificationBtn];
    [self.view addSubview:self.loginBtn];
}

#pragma mark - private

-(void)p_showAlertWithString:(NSString *)string{
//    UIAlertController *alert  = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
//    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        [alert dismissViewControllerAnimated:YES completion:nil];
//    }]];
//    [self presentViewController:alert animated:YES completion:nil];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [TFToast toast:string];
    });
}

#pragma mark - action
/**
 获取验证码
 */
-(void)getVerificationBtnClick:(UIButton *)button{
    
    if (!self.phoneTextField.text.length)
    {
        [self p_showAlertWithString:@"请输入手机号"];
        return;
    }
    
    if (![[WCBUtility share] isMobileNumber:self.phoneTextField.text]) {
        [self p_showAlertWithString:@"请输入正确的手机号"];
        return;
    }
    
    // 调用获取验证码的接口
    [self p_getVerificationRequest];
}

/**
 登录
 */
-(void)loginBtnClick:(UIButton *)button{
    
    
    
//    // 用来调试地址接口
//    [[WCASessionManager manager].requestHeaderFieldValueDictionary setObject:@"718385313074" forKey:@"USERID"];
//
//    WCBAddressListTableViewController *addressVC = [[WCBAddressListTableViewController alloc]init];
//    [self.navigationController pushViewController:addressVC animated:YES];
//    return;

    if (!self.verificationTextField.text.length)
    {
        [self p_showAlertWithString:@"请输入验证码"];
        return;
    }
    
    [self p_loginRequest];
}

- (void)capchaTimerAction:(NSTimer *)timer{
    if (_timeCount>=1) {
        self.getVerificationBtn.userInteractionEnabled = NO;
        [self.getVerificationBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [self.getVerificationBtn setTitle:[NSString stringWithFormat:@"%@(%ld)",NSLocalizedString(@"重新获取", nil),(long)_timeCount--] forState:UIControlStateNormal];
        self.getVerificationBtn.backgroundColor = [UIColor whiteColor];
    }
    else {
        [timer invalidate];
        timer = nil;
        self.getVerificationBtn.userInteractionEnabled = YES;
        self.getVerificationBtn.backgroundColor = [UIColor clearColor];
        [self.getVerificationBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.getVerificationBtn setTitle:NSLocalizedString(@"获取验证码", nil) forState:UIControlStateNormal];
        self.getVerificationBtn.backgroundColor = [UIColor r:49 g:137 b:201];
    }
}

#pragma mark - network
-(void)p_getVerificationRequest{
    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    NSString* time = [NSString stringWithFormat:@"%.f", timeInterval];
    NSDictionary *param = @{@"mobile":self.phoneTextField.text ,
                            @"time":time};
    
    self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0,0,100,100)];
    self.activityIndicatorView.center = self.view.center;
    [self.activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.activityIndicatorView setBackgroundColor:[UIColor lightGrayColor]];
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
    
    [WCASessionManager POST:@"tfmobile/auth/verificationCode"
                 parameters:param
                    success:^(NSURLSessionDataTask *task, id responseObject) {
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            _timeCount = 60.0;
                            //获取验证码
                           self.timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(capchaTimerAction:) userInfo:nil repeats:YES];
                            if ([[responseObject objectForKey:@"status"] boolValue]) {
                                
                                [self.activityIndicatorView stopAnimating];
                            } else {
                                [self p_showAlertWithString:@"获取验证码失败"];
                            }
                        });
                    } failure:^(NSURLSessionDataTask *task, NSError *error) {
                        [self p_showAlertWithString:@"获取验证码失败"];
                    }];
    
}

/**
 登录的网络请求
 */
- (void)p_loginRequest{
    NSDictionary *params = @{@"mobile":self.phoneTextField.text,
                             @"code":self.verificationTextField.text,
                             @"isGzip" :@(0)
                             };
    
    __weak WCBPhoneLoginViewController *weakself = self;
    [WCASessionManager POST:@"tfmobile/auth/validateAndLogin"
                 parameters:params
                    success:^(NSURLSessionDataTask *task, id responseObject) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if ([[responseObject objectForKey:@"status"] boolValue]) {
                                
                                UserModel *userModel =[UserModel modelWithDict: responseObject[@"userInfo"]];
                                [[WCBDataHelper sharedHelper] saveUserModel:userModel];
                                NSString *userId = userModel.userId;
                                [[WCASessionManager manager].requestHeaderFieldValueDictionary setObject:userId forKey:@"USERID"];
                                
                                // 定时器停止  回复获取验证码的按钮
                                [weakself.timer invalidate];
                                weakself.getVerificationBtn.userInteractionEnabled = YES;
                                weakself.getVerificationBtn.backgroundColor = [UIColor clearColor];
                                [weakself.getVerificationBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                                [weakself.getVerificationBtn setTitle:NSLocalizedString(@"获取验证码", nil) forState:UIControlStateNormal];
                                weakself.getVerificationBtn.backgroundColor = [UIColor r:49 g:137 b:201];
                                
                                [weakself p_showAlertWithString:@"登录成功"];
                                
//                                WCBCaptureDataViewController *vc = [[WCBCaptureDataViewController alloc] init];
//                                [weakself.navigationController pushViewController:vc animated:YES];
                                    WCBAddressListTableViewController *addressVC = [[WCBAddressListTableViewController alloc]init];
                                    [self.navigationController pushViewController:addressVC animated:YES];
                            }
                            else{
                                [weakself p_showAlertWithString:@"登录失败"];
                            }
                        });
                    }
                    failure:^(NSURLSessionDataTask *task, NSError *error) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakself p_showAlertWithString:@"登录失败"];
                        });
                    }];
    
}

#pragma mark - lazy -load

- (UITextField *)phoneTextField{
    if (_phoneTextField == nil) {
        _phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(0, 84,[UIScreen width], 70)];
        _phoneTextField.textColor = [UIColor blackColor];
        _phoneTextField.placeholder = @"请输入手机号";
        _phoneTextField.backgroundColor = [UIColor whiteColor];
        _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        _phoneTextField.leftView =  [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        _phoneTextField.layer.cornerRadius = 5;
        _phoneTextField.font = [UIFont systemFontOfSize:25];
        _phoneTextField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 70)];
        _phoneTextField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _phoneTextField;
}

- (UITextField *)verificationTextField{
    
    if (_verificationTextField == nil) {
        _verificationTextField = [[UITextField alloc]initWithFrame:CGRectMake(self.phoneTextField.x,self.phoneTextField.bottom+1 ,[UIScreen width], 70)];
        _verificationTextField.textColor = [UIColor blackColor];
        _verificationTextField.placeholder = @"请输入验证码";
        _verificationTextField.backgroundColor = [UIColor whiteColor];
        _verificationTextField.keyboardType = UIKeyboardTypeNumberPad;
        _verificationTextField.font = [UIFont systemFontOfSize:25];
        _verificationTextField.layer.cornerRadius = 5;
        _verificationTextField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 70)];
        _verificationTextField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _verificationTextField;
}

- (UIButton *)getVerificationBtn{
    if (_getVerificationBtn == nil) {
        _getVerificationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _getVerificationBtn.frame = CGRectMake(self.verificationTextField.right - 200, self.verificationTextField.y +10 , 150, 50);
        _getVerificationBtn.backgroundColor = [UIColor r:49 g:137 b:201];
        [_getVerificationBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_getVerificationBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _getVerificationBtn.layer.cornerRadius = 5;
        [_getVerificationBtn addTarget:self action:@selector(getVerificationBtnClick:) forControlEvents:UIControlEventTouchUpInside];
       

    }
    return _getVerificationBtn;
}

-(UIButton *)loginBtn{
    if (_loginBtn == nil) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginBtn.frame = CGRectMake([UIScreen width]/2 - 150 , self.verificationTextField.bottom + 50, 300, 70);
        _loginBtn.backgroundColor = [UIColor r:49 g:137 b:201];
        [_loginBtn setTitle:@"登录微信小助手" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _loginBtn.layer.cornerRadius = 5;
        _loginBtn.titleLabel.font = [UIFont systemFontOfSize:25];
        [_loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}

- (void)dealloc {
    NSLog(@"\n**************\n%@\n*************\n",NSStringFromClass(self.class));
    
}
@end
